//
//  SinaPictureSelectorVC.swift
//  mySina
//
//  Created by 刘莹 on 2016/11/23.
//  Copyright © 2016年 liuying. All rights reserved.
//

import UIKit

let colCount : CGFloat = 3
let selectorMargin:CGFloat = 4
let selectorCellWidth = (ScreenWidth - (colCount + 1) * selectorMargin) / colCount
//最大数量
private let maxCount = 9

private let reuseIdentifier = "Cell"

//MARK: -
//MARK: - 定义协议
@objc protocol PictureSelectorCellDelegate:NSObjectProtocol{

    //添加图片
    @objc optional func userWillChosePic(cell:SinaPictureSelectorCell?)
    
    //删除图片
    @objc optional func userWillRemovePic(cell:SinaPictureSelectorCell?)
}


class SinaPictureSelectorVC: UICollectionViewController {

    //MARK: -
    //MARK: - 懒加载
    lazy var selectedImages:[UIImage] = [UIImage]()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView!.register(SinaPictureSelectorCell.self, forCellWithReuseIdentifier: reuseIdentifier)

    }
    //MARK: -
    //MARK: - CollectionViewDataSource
    //MARK: -
    //MARK: - 组数
    override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
//        return selectedImages.count + 1
        let delta = self.selectedImages.count == maxCount ? 0:1
        return self.selectedImages.count + delta
    }
    //MARK: -
    //MARK: - cell
    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! SinaPictureSelectorCell
        
        cell.backgroundColor = randomColor()
        //设置代理
        cell.delegate = self
        //给cell设置数据
        if indexPath.item == self.selectedImages.count{//最后一个cell
            cell.image = nil
        }else{
            cell.image = self.selectedImages[indexPath.item]
        }
        
        
        return cell
    }


   

   }
//MARK: -
//MARK: - SinaPictureSelectorVC遵守cell协议的分类
extension SinaPictureSelectorVC:PictureSelectorCellDelegate{

    func userWillChosePic(cell:SinaPictureSelectorCell?) {
        //图片选择控制器
        let picker = UIImagePickerController()
        //modal
        self.present(picker, animated: true, completion: nil)
        //设置picker代理
        picker.delegate = self
    }
    
    func userWillRemovePic(cell:SinaPictureSelectorCell?) {
        //print(#function)
        //1.根据被点击的cell 通过collectionView 获取对应的indexPath
        guard let IndexPath = collectionView?.indexPath(for: cell!) else {
            return
        }
        //2.在数组中删除对应的图片
        self.selectedImages.remove(at: IndexPath.item)
        //3.刷新数据
        self.collectionView?.reloadData()
        //4.如果没有图片的时候就隐藏图片视图
        self.view.isHidden = self.selectedImages.count == 0
    }


}
//MARK: -
//MARK: - 自定义cell
class SinaPictureSelectorCell:UICollectionViewCell{
    
    //MARK: -
    //MARK: - 属性
    //代理
    weak var delegate:PictureSelectorCellDelegate?
    //image
    var image:UIImage?{
    
        didSet{
        
            addBtn.setImage(image, for: .normal)
            removeBtn.isHidden = (image == nil)
        }
    }
    //MARK: -
    //MARK: - 懒加载
    //添加按钮
    lazy var addBtn:UIButton = {
    
        let btn = UIButton()
        btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
        btn.imageView?.contentMode = .scaleAspectFill
        return btn
    }()
    
    //移除按钮
    lazy var removeBtn:UIButton = {
        
        let btn = UIButton()
        btn.setImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
        return btn
    }()
    
    //MARK: -
    //MARK: - 重写构造函数
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: -
    //MARK: - 搭建界面
    private func setupUI(){
        
        self.contentView.addSubview(addBtn)
        self.contentView.addSubview(removeBtn)
        
        addBtn.snp.makeConstraints { (make) in
            
            make.edges.equalTo(self)
        }
        removeBtn.snp.makeConstraints { (make) in
            make.right.top.equalTo(self.contentView)
        }
        
        //监听按钮点击事件
        addBtn.addTarget(self, action: #selector(addBtnClick), for: .touchUpInside)
        removeBtn.addTarget(self, action: #selector(removeBtnClick), for: .touchUpInside)
        
    }
    //MARK: -
    //MARK: - 添加按钮的点击事件
     @objc private func addBtnClick(){
        if image != nil {
            //print("已经有图片了")
            return
        }
        delegate?.userWillChosePic?(cell:self)
    }
    //MARK: -
    //MARK: - 移除按钮的点击事件
    @objc private func removeBtnClick(){
    
        self.delegate?.userWillRemovePic?(cell:self)
    }
}
    //MARK: -
    //MARK: - UIIMagePickerController代理
    extension SinaPictureSelectorVC:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
        //实现协议方法
        func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
            
            //1.选择图片
            let image = info[UIImagePickerControllerOriginalImage] as! UIImage
            //2.将图片添加到数组中
            self.selectedImages.append(image.scaleImage(width: ScreenWidth))
            //dismiss控制器
            dismiss(animated: true) { 
                
            }
            //刷新collectionView
            self.collectionView?.reloadData()
            
        }
    }
    
    
    
    
    
    
    
    
    
    
    


